<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@page import="utils.LoggedUser"%>
<%@include file="/jsp/header.jsp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Snake</title>

<style type="text/css">
	<%@ include file="/css/mainPage.css" %>
</style>

<script type="text/javascript">
 	$(document).ready(function() {

 		
 		
 		function showGamesList(data){
 			
 			var length = data.length;
 			var game; 
 			var htmlString = "";
 			
 			$(".row").remove();
 			for(var i = 0; i<length; i++){
 				game = data[i];
 				var disabled = "";
 				
 				if(game.playerList.length >= game.nrOfPlayers)
					{
					disabled = 'disabled';
					}
 				
 				htmlString += "<tr class='row'>"+
 				"<td>"+game.id+"</td>"+
 				"<td>"+game.playerList[0].username+"</td>"+
 				"<td>"+game.description+"</td>"+
 				"<td>"+game.playerList.length+"/"+game.nrOfPlayers+"</td>"+
 				"<td>"+"<input type='button' value='Join' id='"+game.id+"' onclick='window.location.href=\"join?id="+game.id+"\"'"+disabled+"/>"+"</td>"+
 				"</tr>";
 			}
 			console.log(data);
 			$('table').append(htmlString);
 		}
 		
		function getAllOpendedGames() {
			$.ajax({
				type : "POST",
				url : "getAllOpenedGames",
				/*  data: JSON.stringify({
						"username" : username
					}), */
				dataType : "json",
				contentType : "application/json; charset=utf-8"
			}).done(function(data) {
				//console.log(data);
				
				showGamesList(data);
				//$('div#openedGames').html(data.startTime);
			}).fail(function() {
				/*alert();*/
			}).always(function() {
				// alert(data.fullName);
			});
		}

		getAllOpendedGames();

		setInterval(function() {
			getAllOpendedGames();
		}, 2500);
		console.log("ready!");
	}); 
</script>

</head>
<body>
	<h2>Hello World!</h2>

	<%
		LoggedUser loggedUser = (LoggedUser) session
				.getAttribute("LoggedUser");

		if (loggedUser == null) {
			String guest = (String) session.getAttribute("Guest");
	%>
	<%=guest%>
	<%
		} else {
	%>
	<input type="button" value="Create game" onclick="window.location.href='createGame.do'"/>
	<%=loggedUser.getUsername()%>

	<%
		}
	%>
<table>
		<tr>
		<th>ID</th>
		<th>Game Creator</th>
		<th>Description</th>
		<th>Nr of Players/Max Players</th>
		<th>Join</th>
		</tr>
</table>

</body>
</html>
